package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

@Service
@Slf4j
public class userServiceImpl implements UserService {
    //微信登录接口地址
    private String wxLoginUrl="https://api.weixin.qq.com/sns/jscode2session";
    private String grant_type="authorization_code";
    @Autowired
    private WeChatProperties properties;
    @Autowired
    private UserMapper userMapper;
    /**
     * 微信用户登录
     * @param dto
     * @return
     */
    public User wxLogin(UserLoginDTO dto) {
        //1.封装方法 调用微信接口查询openid
        String openId = getOpenId(dto.getCode());
        //2.根据openid判断是否登陆成功
        if(openId == null){
            throw new LoginFailedException("登陆失败");
        }
        //3.查询openid是否已经存在 没有则注册为新用户
        User user = userMapper.queryOpenid(openId);
        if(user == null){
            //注册为新用户
            User newUser = User.builder().openid(openId)
                    .createTime(LocalDateTime.now())
                    .build();
             userMapper.insertUser(newUser);
             log.info("newUser{}",newUser);
        }
        //4.已经存在直接返回
        return user;
    }

    /**
     * 根据微信授权码获取openid
     * @param code
     * @return
     */
    private String getOpenId(String code){

        //调用接口
        HashMap<String, String> map = new HashMap<>();
        map.put("appid",properties.getAppid());
        map.put("secret",properties.getSecret());
        map.put("js_code",code);
        map.put("grant_type",grant_type);
        //返回是一个json数据
        String result = HttpClientUtil.doGet(wxLoginUrl, map);
        //转换json到对象
        JSONObject jsonObject = JSON.parseObject(result);
        String openid =(String) jsonObject.get("openid");
        return openid;
    }
}
